{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "1d16f7bf-9da4-4c55-8ab4-6828bda85496",
   "metadata": {},
   "outputs": [],
   "source": [
    "import numpy as np\n",
    "from sklearn.datasets import load_iris\n",
    "\n",
    "# ① 加载鸢尾花数据集\n",
    "iris = load_iris()\n",
    "X = iris.data  # 特征数据\n",
    "y = iris.target  # 标签数据\n",
    "\n",
    "# ② 随机打乱数据集（特征和标签同步打乱）\n",
    "seed = 42  # 随机数种子，可根据需要修改\n",
    "np.random.seed(seed)  # 固定种子，确保特征和标签打乱方式一致\n",
    "\n",
    "# 生成索引并打乱\n",
    "indices = np.arange(X.shape[0])\n",
    "np.random.shuffle(indices)\n",
    "\n",
    "# 按打乱后的索引重新排列特征和标签\n",
    "X_shuffled = X[indices]\n",
    "y_shuffled = y[indices]\n",
    "\n",
    "# ③ 划分训练集和测试集（这里使用8:2的比例）\n",
    "split_ratio = 0.8  # 训练集占比\n",
    "split_idx = int(X_shuffled.shape[0] * split_ratio)\n",
    "\n",
    "X_train = X_shuffled[:split_idx]\n",
    "y_train = y_shuffled[:split_idx]\n",
    "X_test = X_shuffled[split_idx:]\n",
    "y_test = y_shuffled[split_idx:]\n",
    "\n",
    "# 转换特征值数据类型为float32\n",
    "X_train = X_train.astype(np.float32)\n",
    "X_test = X_test.astype(np.float32)\n",
    "\n",
    "# 标准化处理（均值为0）\n",
    "# 注意：标准化的均值和标准差必须基于训练集计算，避免数据泄露\n",
    "mean = np.mean(X_train, axis=0)  # 计算训练集每个特征的均值\n",
    "X_train = X_train - mean  # 训练集标准化（均值为0）\n",
    "X_test = X_test - mean    # 测试集使用训练集的均值进行标准化\n",
    "\n",
    "# 验证结果\n",
    "print(\"训练集特征形状：\", X_train.shape)\n",
    "print(\"测试集特征形状：\", X_test.shape)\n",
    "print(\"训练集特征数据类型：\", X_train.dtype)\n",
    "print(\"训练集各特征均值（标准化后）：\", np.round(np.mean(X_train, axis=0), 6))  # 接近0\n",
    "print(\"测试集各特征均值（标准化后）：\", np.round(np.mean(X_test, axis=0), 6))   # 不一定为0，因使用训练集均值"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python [conda env:base] *",
   "language": "python",
   "name": "conda-base-py"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.13.5"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
